package cn.itcast.mobilebrowser.database;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.itcast.mobilebrowser.dao.BookMarkDao;
import cn.itcast.mobilebrowser.dao.HistoryDao;
import cn.itcast.mobilebrowser.model.BookMark;
import cn.itcast.mobilebrowser.model.History;

@Database(entities = {BookMark.class, History.class}, version = 1)
@TypeConverters({DateConverter.class})
public abstract class BrowserDatabase extends RoomDatabase {

    public abstract BookMarkDao getBookMarkDao();
    public abstract HistoryDao getHistoryDao();

    private static final String DATABASE_NAME = "BrowserDatabase";
    private static volatile BrowserDatabase INSTANCE;
    private static final int NUMBER_OF_THREAD = 5;

    // 线程池用于执行数据库操作
    public static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUMBER_OF_THREAD);

    /**
     * 单例模式获取数据库实例
     */
    public static BrowserDatabase getDataBase(final Context context) {
        if (INSTANCE == null) {
            synchronized (BrowserDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            BrowserDatabase.class, DATABASE_NAME).build();
                }
            }
        }
        return INSTANCE;
    }
}
